package cn.itcast.bos.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;


import cn.itcast.bos.action.common.BaseAction;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
		
	//注入AreaService
	@Autowired
	private AreaService areaService;
	
	//接收上传文件
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

	//批量导入区域数据导入
	@Action(value="area_batchImport",results={@Result(name="success",type="redirect",location="./pages/base/area.html")})
	public String importArea() throws IOException{
		
		//定义一个集合用来接收封装好的多个Arae对象
		List<Area> list = new ArrayList<Area>();
		
		//编写解析代码逻辑
		
		//1.加载Excel文件对象
		@SuppressWarnings("resource")
		HSSFWorkbook hssWordkbook = new HSSFWorkbook(new FileInputStream(file));
		
		//2.读取一页sheet
		//通过索引获取指定页sheet
		HSSFSheet sheet = hssWordkbook.getSheetAt(0);
		
		//3.读取sheet中每一行
		//循环遍历读取
		for (Row row : sheet) {
			
			//一行数据对应一个区域对象
			if(row.getRowNum()==0){
				//跳过第一行（通过判断该行的索引是否为0）
				continue;
			}
			
			//跳过空行
			if(row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				//通过判断该行的第一个单元格是否为空来判断该行是否为空行
				
				//跳过空行
				continue;
			}
			
			//将每一行数据封装为一个Area对象
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			//由于一个sheet可能有多行数据，所以这里需要用一个集合来接收封装好的area对象
			list.add(area);			
		}
		
		//调用业务层完成导入操作
		areaService.batchImport(list);
		return SUCCESS;
	}
	
	//区域条件分页查询
	
	@Action(value="area_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		
		//构造分页查询对象
		Pageable pageable = new PageRequest(page-1, rows);
		
		//构造条件查询对象
		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				//定义一个集合用于保存多个条件
				List<Predicate> list = new ArrayList<Predicate>();
				
				//对省份进行模糊查询
				//先判断Area的省份是否为空，为空则不用判断了
				if(StringUtils.isNotBlank(model.getProvince())){
					
					Predicate p1 = cb.like(root.get("province").as(String.class),
							"%"+model.getProvince()+"%");
					
					//讲条件对象保存到List集合
					list.add(p1);
				}
				
				//对城市进行模糊查询
				if(StringUtils.isNotBlank(model.getCity())){
					Predicate p2 = cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
					
					//讲条件对象保存到List集合
					list.add(p2);
				}
				
				//对区进行模糊查询
				if(StringUtils.isNotBlank(model.getDistrict())){
					Predicate p3 = cb.like(root.get("district").as(String.class), "%"+model.getDistrict()+"%");
					
					//讲条件对象保存到List集合
					list.add(p3);
				}
				
				//将多个条件对象存入集合转换为一个条件对象数组返回
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		
		//调用业务层完成分页查询,返回一个Page对象
		Page<Area> pageData = areaService.pageQuery(specification,pageable);
		
		//将结果压入值栈
		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}
}
